package cn.gson.zuche.model.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import cn.gson.zuche.model.bean.Car;
import cn.gson.zuche.model.jdbc.MySqlDb;
import cn.gson.zuche.model.jdbc.ParamHandler;
import cn.gson.zuche.model.jdbc.ResultHandler;

public class Cardao implements ResultHandler<Car> {
	private MySqlDb db = MySqlDb.getInstance();

	/**
	 * 更改车状态
	 * @param c
	 * @return
	 * @throws SQLException
	 */
	public boolean updatecheztai(String chepaihao,String zt) throws SQLException {
		String sql = "update car set car_zt_ids='"+zt+"' where car_license_id='"+chepaihao+"'";
		return db.executeUpdate(sql) > 0;
	}
	/**
	 * 获取空闲车的库存
	 * @param c
	 * @return
	 * @throws SQLException
	 */
	public List<Car> huoqukucun(String name) throws SQLException {
		String sql = "SELECT count(car_zt_ids) as car_num  from car WHERE car_type_ids=(SELECT car_type_id from car_type WHERE car_type_name='"+name+"') and car_zt_ids='1'";
		return  db.executeQuery(sql, this);
	}
	/**
	 * 获取kucun
	 * @param c
	 * @return
	 * @throws SQLException
	 */
	public List<Car> nakucun(String chepaihao) throws SQLException {
		String sql = "SELECT count(car_zt_ids) as car_num from car WHERE car_type_ids=(SELECT car_type_ids from car WHERE car_license_id='"+chepaihao+"') and car_zt_ids='1'";
		return  db.executeQuery(sql, this);
	}
	
	public boolean insert(final Car c) throws SQLException {
		String sql = "insert into car(car_license_id,car_type_ids,car_zt_ids) values(?,?,?)";
		return db.executeUpdate(sql, new save(c)) > 0;
	}
	public List<Car> selectcount(String id) throws SQLException {
		String sql = "SELECT COUNT(car_type_ids) as car_type_ids  from car WHERE car_type_ids='"+id+"' and car_zt_ids='1'";
		return  db.executeQuery(sql, this);
	}

	private class save implements ParamHandler {
		Car c;
		public save(Car c) {
			this.c = c;
		}
		public void doHander(PreparedStatement pStatement) throws SQLException {
			pStatement.setString(1, c.getCarlicenseid());
			pStatement.setString(2, c.getCartypeids());
			pStatement.setString(3, c.getCarztids());
		}

	}

	@Override
	public Car doHander(Map<String, Object> row) {
		Car c = new Car();
		c.setCarlicenseid((String) row.get("car_license_id"));
		c.setCarstoreid((String) row.get("cat_store_id"));
		c.setCartypeids(row.get("car_type_ids")+"");
		c.setCarztids((String) row.get("car_zt_ids"));
		if(row.get("car_num")!=null){
		c.setNum( Integer.parseInt(row.get("car_num")+""));
		}
		return c;
	}

}
